package com.zhengx.baselib;


import android.app.Application;
import android.content.res.Configuration;
import android.support.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

/**
 * name：ModulesInitializer
 * class: 子模块初始化Application
 * author: zhengx
 * create_time: 2019/1/18
 */
public class ModulesInitializer {

    private Application application;

    private List<IApplication> modulesInstances;

    public ModulesInitializer(@NonNull String[] modulesPackageName, @NonNull Application application) {
        this.application = application;
        modulesInstances = new ArrayList<>();
        for (String s : modulesPackageName) {
            try {
                Class<?> clazz = Class.forName(s);
                Object obj = clazz.newInstance();
                if (obj instanceof IApplication){
                    modulesInstances.add((IApplication) obj);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    public void onCreate() {
        for (IApplication modulesInstance : modulesInstances) {
            modulesInstance.onCreate(application);
        }
    }

    public void onTerminate() {
        for (IApplication modulesInstance : modulesInstances) {
            modulesInstance.onTerminate(application);
        }
    }

    public void onConfigurationChanged(Configuration configuration) {
        for (IApplication modulesInstance : modulesInstances) {
            modulesInstance.onConfigurationChanged(application, configuration);
        }
    }

    public void onLowMemory() {
        for (IApplication modulesInstance : modulesInstances) {
            modulesInstance.onLowMemory(application);
        }
    }

    public void onTrimMemory(int level) {
        for (IApplication modulesInstance : modulesInstances) {
            modulesInstance.onTrimMemory(application, level);
        }
    }
}
